package com.rp.system.corn.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rp.common.result.ResultDTO;
import com.rp.system.corn.entity.QuartzJob;
import com.rp.system.corn.enums.JobStatus;
import com.rp.system.corn.mapper.JobMapper;
import com.rp.system.corn.service.JobService;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class JobServiceImpl implements JobService {

    private static final String TRIGGER_IDENTITY = "trigger";

    @Autowired
    private Scheduler scheduler;

    @Autowired
    private JobMapper jobMapper;


    @Override
    public IPage<QuartzJob> listQuartzJob(String jobName, Integer pageNum, Integer pageSize) {
        return jobMapper.pageJob(new Page<>(pageNum, pageSize),jobName);
    }

    @Override
    public ResultDTO saveJob(QuartzJob quartz){
        try {
            schedulerJob(quartz);

            quartz.setTriggerState(JobStatus.RUNNING.getStatus());
            quartz.setOldJobGroup(quartz.getJobGroup());
            quartz.setOldJobName(quartz.getJobName());
            jobMapper.saveJob(quartz);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultDTO.error();
        }
        return ResultDTO.success();
    }

    @Override
    public ResultDTO triggerJob(String jobName, String jobGroup) {
        JobKey key = new JobKey(jobName,jobGroup);
        try {
            scheduler.triggerJob(key);
        } catch (SchedulerException e) {
            e.printStackTrace();
            return ResultDTO.error();
        }
        return ResultDTO.success();
    }

    @Override
    public ResultDTO pauseJob(String jobName, String jobGroup) {
        JobKey key = new JobKey(jobName,jobGroup);
        try {
            scheduler.pauseJob(key);
            jobMapper.updateJobStatus(jobName, jobGroup, JobStatus.PAUSED.getStatus());
        } catch (SchedulerException e) {
            e.printStackTrace();
            return ResultDTO.error();
        }
        return ResultDTO.success();
    }

    @Override
    public ResultDTO resumeJob(String jobName, String jobGroup) {
        JobKey key = new JobKey(jobName,jobGroup);
        try {
            scheduler.resumeJob(key);
            jobMapper.updateJobStatus(jobName,jobGroup, JobStatus.RUNNING.getStatus());
        } catch (SchedulerException e) {
            e.printStackTrace();
            return ResultDTO.error();
        }
        return ResultDTO.success();
    }

    @Override
    public ResultDTO removeJob(String jobName, String jobGroup) {
        try {
            TriggerKey triggerKey = TriggerKey.triggerKey(TRIGGER_IDENTITY + jobName, jobGroup);
            scheduler.pauseTrigger(triggerKey);                                 // 停止触发器
            scheduler.unscheduleJob(triggerKey);                                // 移除触发器
            scheduler.deleteJob(JobKey.jobKey(jobName, jobGroup));              // 删除任务
            jobMapper.removeQuartzJob(jobName, jobGroup);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultDTO.error();
        }
        return ResultDTO.success();
    }

    @Override
    public QuartzJob getJob(String jobName, String jobGroup) {
        QuartzJob job = jobMapper.getJob(jobName, jobGroup);
        return job;
    }

    @Override
    public ResultDTO updateJob(QuartzJob quartz) {
        try {

            scheduler.deleteJob(new JobKey(quartz.getOldJobName(),quartz.getOldJobGroup()));
            schedulerJob(quartz);

            quartz.setOldJobGroup(quartz.getJobGroup());
            quartz.setOldJobName(quartz.getJobName());
            jobMapper.updateJob(quartz);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultDTO.error();
        }
        return ResultDTO.success();
    }

    @Override
    public void schedulerJob(QuartzJob job) {
        //构建job信息
        try {
            Class cls = Class.forName(job.getJobClassName());
            // cls.newInstance(); // 检验类是否存在
            JobDetail jobDetail = JobBuilder.newJob(cls).withIdentity(job.getJobName(),job.getJobGroup())
                    .withDescription(job.getDescription()).build();

            // 触发时间点
            CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(job.getCronExpression().trim());
            Trigger trigger = TriggerBuilder.newTrigger().withIdentity(TRIGGER_IDENTITY + job.getJobName(), job.getJobGroup())
                    .startNow().withSchedule(cronScheduleBuilder).build();
            //交由Scheduler安排触发
            scheduler.scheduleJob(jobDetail, trigger);
        }catch (Exception e){
            e.printStackTrace();
        }


    }

    @Override
    public List<QuartzJob> listJobByGroup(String jobGroup) {
        return jobMapper.listJobByGroup(jobGroup);
    }
}